package com.atguigu.lease.admin.controller;

import com.atguigu.lease.admin.service.AttrKeyService;
import com.atguigu.lease.admin.service.AttrValueService;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.bean.AttrKey;
import com.atguigu.lease.model.bean.AttrValue;
import com.atguigu.lease.model.vo.AttrKeyVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "房间基本信息-属性和属性值管理模块")
@RestController
@RequestMapping("/admin/attr")
public class AttrKeyController {
    @Autowired
    private AttrKeyService attrKeyService;
    @Autowired
    private AttrValueService attrValueService;

    @Operation(summary = "1、查询所有属性和属性值列表")
    @GetMapping("/list")
    public Result<List<AttrKeyVo>> list(){
        //mp的通用service和通用mapper只能生成单表CRUD的方法
        //需要自定义sql实现:
        List<AttrKeyVo>  attrKeyVos = attrKeyService
                .listAttrKeyVos();

        return Result.ok(attrKeyVos);
    }

    ///admin/attr
    @Operation(summary = "2、新增attrKey")
    @PostMapping("/key/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody AttrKey attrKey){
        return Result.ok(attrKeyService.saveOrUpdate(attrKey));
    }
    ///admin/attr/value/saveOrUpdate
    @Operation(summary = "3、新增attrValue")
    @PostMapping("/value/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody AttrValue attrValue){
        return Result.ok(attrValueService.saveOrUpdate(attrValue));
    }
    ///admin/attr/value/deleteById?id=1
    @Operation(summary = "4、根据id删除attrValue")
    @DeleteMapping("/value/deleteById")
    public Result deleteValueById(@RequestParam Long id){
        return Result.ok(attrValueService.removeById(id));
    }
    ///admin/attr/key/deleteById?attrKeyId=1
    @Operation(summary = "5、根据attrKeyId删除attrKey")
    @DeleteMapping("/key/deleteById")
    public Result deleteKeyById(@RequestParam Long attrKeyId){
        //判断：如果attrKeyId 没有可用的attrValue才可以删除
        // select count(1) from attr_value where attr_key_id = #{attrKeyId} and is_deleted = 0
        long count = attrValueService.count(Wrappers.lambdaQuery(AttrValue.class)
                .eq(AttrValue::getAttrKeyId, attrKeyId));
        if(count>0){
            //            throw new RuntimeException("当前属性下存在属性值！！");
            return Result.error(ResultCodeEnum.DELETE_ERROR);
        }
        return Result.ok(attrKeyService.removeById(attrKeyId));
    }
}
